//打包 npm run pack-builder
var app = new Vue({
    el: '#app',
    data: {
        isLoading: false,
        title: '精彩推荐',
        currentNav: -1,
        navs: [{
            key: 'meishi',
            label: '美食'
        },{
            key: 'xiaoqingxin',
            label: '小清新'
        },{
            key: 'zhiwu',
            label: '植物'
        },{
            key: 'youxi',
            label: '游戏'
        },{
            key: 'shuaige',
            label: '帅哥'
        },{
            key: 'qiche',
            label: '汽车'
        },{
            key: 'tiyu',
            label: '体育'
        },{
            key: 'junshi',
            label: '军事'
        },{
            key: 'jiaju',
            label: '家具'
        },{
            key: 'fengjing',
            label: '风景'
        },{
            key: 'wmyjdmbz',
            label: '动漫'
        },{
            key: 'wallpaper_0_0_0_1',
            label: '其他'
        }],
        list: [],
        currentPage: 1,
        pages: [],
        alert:{
            show:false,
            title:'',
            content:''
        },
        dialog:{
            show:false,
            isCircle:false,
            interval:5 //单位：分钟
        },
        isSetCircle:false
    },
    created: function (){
        this.getScreen()
        // this.setTitle();
        // this.fill();
    },
    mounted: function(){
        console.log('加载完成..');
        this.show('diannaozhuomian')
        this.circleWallpaper();
    },
    methods: {
        getScreen: function (){
            var height = window.screen.height;
            var width = window.screen.width;
            var screen = width + '*' + height;
            document.getElementById("screen").innerHTML = screen;
        },
        setTitle: function(key) {
            $this = this;
            this.navs.forEach(item => {
                if (item.key == key){
                    $this.title = item.label + '桌面壁纸';
                    return false;
                }
            });
        },
        fill: function(){
            for (const i in 15) {
                this.list.append({
                    img_url: 'placeholder.jpg',
                    set_btn_label: '设置壁纸'
                });
            }
        },
        show: function(key){
            this.currentPage = 1;
            this.currentNav = key;
            this.setTitle(key);
            this.loadData(key);
        },
        loadData: function (key){
            this.fill();
            this.isLoading = true;
            this.list = [];
            this.pages = [];
            console.log('当前抓取页数：' + this.currentPage)
            if(key == 'wallpaper_0_0_0_1'){
                href = 'http://www.win4000.com/wallpaper_0_0_0_{0}.html';
                href = href.replace('{0}', this.currentPage);
            }else{
                var href = 'http://www.win4000.com/zt/{0}{1}.html';
                href = href.replace('{0}',key);
                if(Number(this.currentPage) > 1){
                    href = href.replace('{1}','_' + this.currentPage);
                }else{
                    href = href.replace('{1}','');
                }
            }
            superagent.get(href).end((error,response)=>{
                this.isLoading = false;
                //获取页面文档数据
                var content = response.text;
                if(content == null || content == ''){
                    return ;
                }
                //cheerio也就是nodejs下的jQuery  将整个文档包装成一个集合，定义一个变量$接收
                var $ = cheerio.load(content);
                //定义一个空数组，用来接收数据
                var tab_tj = $(".Left_bar div.tab_tj").get(0);
                //抓取内容
                $(tab_tj).find("ul li").each((index,el)=>{
                    if(index < 15){
                        var img_url = $(el).find("a").children("img").attr("data-original");
                        console.log(img_url)
                        this.list.push({img_url:img_url,set_btn_label: '设置壁纸'})
                    }
                });
                //抓取分页栏
                var hasNextPage = false;
                $(".Left_bar div.pages div").children().each((index,el)=>{
                    var page = $(el).text();
                    console.log(page);
                    this.pages.push(page);
                });
                console.log(this.pages);
            });
            this.currentNav = key;
        },
        showByPage: function(currentPage){
            this.currentPage = Number(currentPage);
            this.loadData(this.currentNav);
        },
        showByPrevPage: function(currentPage){
            this.currentPage = Number(currentPage) - 1;
            this.loadData(this.currentNav);
        },
        showByNextPage: function(currentPage){
            this.currentPage = Number(currentPage) + 1;
            this.loadData(this.currentNav);
        },
        setWallpaper: function(url,index){
            this.list[index].set_btn_label = '切换中...';
            url = url.replace('_270_185','');
            console.log(url);
            $this = this;
            this.download(url, function(res){
                console.log(res);
                console.log('下载成功');
                /**
                 * 
                 * cmd.get(
                    'call wallpaper.exe',
                    function(err, data, stderr){
                        if (!err) {
                            console.log('the node-cmd cloned dir contains these files :\n\n',data)
                            $this.list[index].set_btn_label = '设置壁纸';
                        } else {
                            console.log('error', err)
                        }
                    }
                );
                 */
                exec('call wallpaper.exe', function(err,stdout,stderr){
                    if(err) {
                        console.log('call wallpaper.exe error:'+stderr);
                    } else {
                        $this.list[index].set_btn_label = '设置壁纸';
                        console.log('壁纸设置成功.');
                    }
                });    
            });
        },
        previewWallpaper: function(url){
            this.showAlert('提示','看看就得啦，要啥自行车...');
        },
        download: function(img_src, callback){
            request.head(img_src,function(err,res,body){
                if(err){
                    console.log(err);
                }
                callback(res);
            });
             
            var img_filename = 'btf_wallpaper_20200322.jpg';  
            request(img_src).pipe(fs.createWriteStream('./'+ img_filename));  
        },
        min:function(){
            console.log('call:min');
            ipcRenderer.send('min');
        },
        max:function(){
            console.log('call:max');
            ipcRenderer.send('max');
        },
        close:function(){
            console.log('call:close');
            ipcRenderer.send('close');
        },
        set:function(){
            console.log('设置:');
            console.log(this.dialog.isCircle)
            var json = {"isCircle":this.dialog.isCircle,"interval":this.dialog.interval};
            localStorage.setItem("set_cache",JSON.stringify(json));
            this.closeDialog();
            this.circleWallpaper();
        },
        circleWallpaper:function(){
            var i = 0;
            var interval = 5;
            if(this.isSetCircle){
                clearInterval(this.isSetCircle);
                i = 0;
            }
            var that = this;
            var value = localStorage.getItem("set_cache");
            if(value){
                var json = JSON.parse(value);
                if(!json.isCircle){
                    return;
                }
                interval = Number(json.interval);
            }
            this.isSetCircle = setInterval(function(){
                var len = that.list.length;
                if(i >= len){
                    i = 0;
                }
                var url = that.list[i].img_url;
                url = url.replace('_270_185','');
                that.download(url, function(res){
                    console.log('轮询切换：下载成功');
                    exec('call wallpaper.exe', function(err,stdout,stderr){
                        if(err) {
                            console.log('轮询切换：call wallpaper.exe error:'+stderr);
                        } else {
                            console.log('轮询切换：壁纸设置成功.');
                        }
                    });    
                });
                i++; 
            },interval*1000*60);
        },
        showSet:function(){
            console.log('打开设置....');
            this.showDialog();
        },
        showAlert:function(title,message){
            this.alert.title = title;
            this.alert.content = message;
            this.alert.show = true;
        },
        closeAlert:function(){
            this.alert.show = false;
        },
        showDialog:function(){
            var value = localStorage.getItem("set_cache");
            if(value){
                var json = JSON.parse(value);
                this.dialog.isCircle = json.isCircle
                this.dialog.interval = json.interval;
            }
            this.dialog.show = true;
        },
        closeDialog:function(){
            this.dialog.show = false;
        }
    }
})